<template>
	<div class="users-section">
		<div class="table-container">
			<el-table 
				:data="paginatedUserlist" 
				style="width: 100%"
				:max-height="500"
				@selection-change="handleSelectionChange"
			>
				<el-table-column prop="id" label="ID" min-width="80" align="center" />
				<el-table-column prop="openid" label="微信openid" min-width="120" />
				<el-table-column prop="unionid" label="微信unionid" min-width="140" />
				<el-table-column prop="nickname" label="用户昵称" min-width="120" />
				<el-table-column prop="avatar" label="头像" min-width="100">
					<template #default="{ row }">
						<img :src="getAvatarUrl(row.avatar)" alt="头像" style="
                width: 60px;
                height: 60px;
                border-radius: 50%;
                object-fit: cover;
              " @error="handleImageError" />
					</template>
				</el-table-column>

				<el-table-column prop="status" label="状态" min-width="100">
					<template #default="{ row }">
						<el-tag :type="row.status === 1 ? 'success' : 'danger'">
							{{ row.status === 1 ? '正常' : '封禁' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createdTime" label="创建时间" min-width="180" :formatter="formatDateTime" />
				<el-table-column prop="updatedTime" label="最后登录时间" min-width="180" :formatter="formatDateTime" />
				<el-table-column label="操作" min-width="120" align="center">
					<template #default="{ row }">
						<div class="action-buttons">
							<el-button size="small" type="success" @click="viewUserUsage(row)" plain class="action-btn">使用记录</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
		</div>
		
		<!-- 分页组件 -->
		<div class="pagination-container">
			<el-pagination
				v-model:current-page="currentPage"
				v-model:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100]"
				:total="props.userlist.length"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</div>

		<!-- 查看用户使用记录对话框 -->
		<el-dialog v-model="usageDialogVisible" title="用户使用记录" width="90%" :close-on-click-modal="false">
			<UserUsageRecords v-if="usageDialogVisible" :openid="selectedUserOpenid" />
			<template #footer>
				<el-button @click="usageDialogVisible = false">关闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<style scoped>
.action-buttons {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8px;
	width: 100%;
}

.action-btn {
	width: 80px !important;
	height: 32px !important;
	font-size: 12px !important;
	padding: 0 !important;
	margin: 0 !important;
}

.pagination-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 20px 0;
	background: #fff;
	border-radius: 8px;
	margin-top: 16px;
	box-shadow: 0 2px 8px rgba(25, 118, 210, 0.1);
}


</style>

<script setup>
	import {
		ref,
		computed,
		watch
	} from "vue";

	import UserUsageRecords from "./UserUsageRecords.vue";
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";
	import usersapi from "../api/usersapi";

	const emit = defineEmits(['updateUserList']);

	// 响应式数据声明
	const usageDialogVisible = ref(false);
	const selectedUserOpenid = ref("");

	const props = defineProps({
		userlist: {
			type: Array,
			required: true
		}
	});

	// 分页相关数据
	const currentPage = ref(1);
	const pageSize = ref(20);
	const selectedRows = ref([]);

	// 计算分页后的数据
	const paginatedUserlist = computed(() => {
		const start = (currentPage.value - 1) * pageSize.value;
		const end = start + pageSize.value;
		return props.userlist.slice(start, end);
	});

	// 分页事件处理
	const handleSizeChange = (val) => {
		pageSize.value = val;
		currentPage.value = 1; // 重置到第一页
	};

	const handleCurrentChange = (val) => {
		currentPage.value = val;
	};

	const handleSelectionChange = (selection) => {
		selectedRows.value = selection;
	};

	// 监听数据变化，重置分页
	watch(() => props.userlist, () => {
		currentPage.value = 1;
	}, { deep: true });

	// 获取头像URL，添加域名前缀
	const getAvatarUrl = (avatar) => {
		if (!avatar || avatar === '' || avatar === 'null' || avatar === 'undefined') {
			// 返回默认头像
			return '';
		}
		
		// 如果已经是完整的URL（包含http或https），直接返回
		if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
			return avatar;
		}
		
		// 添加域名前缀
		const baseUrl = 'http://tool_back.connectsphere.top';
		return baseUrl + (avatar.startsWith('/') ? avatar : '/' + avatar);
	};

	// 处理图片加载错误
	const handleImageError = (event) => {
		// 设置默认头像
		event.target.src = '';
	};

	// 格式化时间
	const formatDateTime = (row, column, cellValue) => {
		if (!cellValue) return '-';

		try {
			// 如果已经是Date对象或时间戳
			const date = new Date(cellValue);
			if (isNaN(date.getTime())) {
				// 尝试处理字符串格式
				if (typeof cellValue === 'string') {
					// 处理可能的不同时间格式
					const parsedDate = new Date(cellValue.replace(/-/g, '/'));
					if (!isNaN(parsedDate.getTime())) {
						return formatDate(parsedDate);
					}
				}
				return cellValue; // 无法解析则返回原值
			}
			return formatDate(date);
		} catch (e) {
			console.error('格式化时间出错:', e);
			return cellValue;
		}
	};

	// 辅助格式化函数
	const formatDate = (date) => {
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		const seconds = String(date.getSeconds()).padStart(2, '0');

		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	};

	// 查看用户使用记录
	const viewUserUsage = (user) => {
		selectedUserOpenid.value = user.openid;
		usageDialogVisible.value = true;
	};
</script>
